package multithreading;

/**
 * 创建两个线程，一个线程打印奇数，另一个线程打印偶数，要求两个线程交替打印 1 - 100 的数字。
 */
public class ParityPrinting {

    private volatile int count = 1;
    private Object lock = new Object();
    public void core() {
        Thread thred1 = new Thread(() -> {
            while (count < 100) {
                synchronized(lock) {
                    if (count % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + " " + count);
                    count++;

                    }
                    lock.notify();
                    // 释放锁 并 等待
                    try {
                        if (count < 100) {
                            lock.wait();
                        }
                    } catch(InterruptedException exception) {
                        exception.printStackTrace();
                    }
                }
                
            }
        }, "odd Thread");
        Thread thread2 = new Thread(() -> {
            while (count < 100) {
                 synchronized(lock) {
                if (count % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + " " + count);
                count++;
                }
                lock.notify();
                // 释放锁 并 等待
                try {
                   if (count < 100) {
                       lock.wait();
                   }
               } catch(InterruptedException exception) {
                   exception.printStackTrace();
               }
               }
            }
           
        }, "Even Thread");
        thread2.start();
        thred1.start();

        try {
            thred1.join();
            thread2.join();
        } catch(InterruptedException exception) {
            exception.printStackTrace();
        }
        
        
    }

    public static void main(String[] args) {
        ParityPrinting parityPrinting = new ParityPrinting();
        parityPrinting.core();
    }
}
